package zhtt.controller;

import com.gitee.zhtt.base.DateTimeUtils;
import com.gitee.zhtt.third.json.JsonUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import zhtt.entity.Blog;
import zhtt.utils.HttpUtil;

import java.io.*;
import java.util.Date;
import java.util.Map;

@Controller
public class PageController {

    @RequestMapping("/test.html")
    public String test2(Model model) {

        model.addAttribute("msg", "标准变量表达式");
        model.addAttribute("html", "<span style='color:red;'>这里面是html片段</span>");
        model.addAttribute("thValue", "admin");
        model.addAttribute("thSrc", "/images/logo.png");
        model.addAttribute("thHref", "/images/logo.png");
        String[] strs = {"内容一", "内容二"};
        model.addAttribute("thEach", strs);

        Blog blog=new Blog();
        blog.setId(1);
        blog.setName("yixin");
        blog.setPwd("123");

        model.addAttribute("blog",blog);
        return "test";
    }

    /**
     * bootstrap4
     * @param model
     * @return
     * @throws IOException
     */
    @RequestMapping("/home.html")
    public String home(Model model) throws IOException {
        homeData(model);
        return "home";
    }

    /**
     * bootstrap5
     * @param model
     * @return
     * @throws IOException
     */
    @RequestMapping("/home-v5.html")
    public String homev5(Model model) throws IOException {
        homeData(model);
        return "home-v5";
    }

    private void homeData(Model model) throws IOException {
        String loginUserInfo = null;
        //String loginUserInfo = HttpUtil.httpRequest("http://localhost:8013/getLoginUser");
        //System.out.println(loginUserInfo);
        // 读取本地的文件
        String filePath = "/static/data/home.json";
        ClassPathResource readFile = new ClassPathResource(filePath);
        // 获取文件对象
        File file = readFile.getFile();
        // 获取文件流
        InputStream inputStream = readFile.getInputStream();
        Reader reader = new InputStreamReader(inputStream);
        int ch = 0;
        StringBuffer stringBuffer = new StringBuffer();
        while ((ch = reader.read()) != -1){
            stringBuffer.append((char) ch);
        }
        inputStream.close();
        reader.close();
        String jsonString = stringBuffer.toString();
        Map<String, Object> map =JsonUtils.toMap(jsonString);
        String generateTime = DateTimeUtils.format(new Date());
        System.out.println("generateTime: "+generateTime);
        model.addAttribute("generateTime", generateTime);
        model.addAttribute("loginUserInfo", loginUserInfo);
        model.addAttribute("homeData",map);
    }

}
